﻿using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using Furion.FriendlyException;
using HOPU.OnlineSchool.Application.Subjects.Dto;
using HOPU.OnlineSchool.Core;
using Mapster;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace HOPU.OnlineSchool.Application.Subjects.Services
{
    public class SubjectService: ISubjectService, ITransient
    {
        private readonly IRepository<EduSubject> _subjectRepository;

        public SubjectService(IRepository<EduSubject> subjectRepository)
        {
            this._subjectRepository = subjectRepository;
        }
        //获取课程目录的 树形数据
        public async Task<List<SubjectTreeDto>> GetSubjectTreeSync()
        {
            var list = await _subjectRepository.Entities.AsNoTracking().ToListAsync();
            var oneList = list.Where(e => e.ParentId == "0");
            var treeList = new List<SubjectTreeDto>();
            foreach (var item in oneList)
            {
                var treeDto = new SubjectTreeDto() { Id = item.Id, Title = item.Title };
                var children = list.Where(e => e.ParentId == item.Id).Select(e => new SubjectSubDto() { Id = e.Id, ParentId = e.ParentId, Title = e.Title }).ToList();
                treeDto.Children = children;
                treeList.Add(treeDto);
            }
            return treeList;
        }
        /// <summary>
        /// 添加课程分类
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<string> AddAsync(SubjectSubDto dto)
        {
            var model = dto.Adapt<EduSubject>();
            model.Id = YitIdHelper.NextId().ToString();
            await _subjectRepository.InsertAsync(model);
            return "添加成功";
        }
        /// <summary>
        /// 删除课程分类
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<string> DeleteAsync(string id)
        {
            var model = await _subjectRepository.FirstOrDefaultAsync(e => e.Id == id);
            if (model == null)
                throw Oops.Oh("该课程分类未找到");
            await _subjectRepository.DeleteAsync(model);

            var children = _subjectRepository.Where(e => e.ParentId == model.Id);
            if (children.Any())
            {
                await _subjectRepository.DeleteAsync(children);
            }
            return "删除成功";

        }
    }
}
